package com.generator.mybatis.generator.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

public class CreateTemplateUtil {
//    public static void createFile(String templatePath, String filePath, IContext data) throws IOException, TemplateException {
//        /*
//        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
//        resolver.setPrefix("ganerator/");//模板所在目录，相对于当前classloader的classpath。
//        resolver.setSuffix(".html");//模板文件后缀
//        TemplateEngine templateEngine = new TemplateEngine();
//        templateEngine.setTemplateResolver(resolver);
//        new File(new File(filePath).getParent()).mkdirs();
//        FileWriter write = new FileWriter(filePath);
//        String code=templateEngine.process(templatePath, data).replaceAll("&quot;", "\"");
//        */
//        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
//        cfg.setDirectoryForTemplateLoading(new File("E:\\generator\\src\\main\\resources\\ganerator"));
//        cfg.setDefaultEncoding("UTF-8");
//        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
//        cfg.setLogTemplateExceptions(false);
//        cfg.setWrapUncheckedExceptions(true);
//        Template temp = cfg.getTemplate(templatePath+".html");
//        StringWriter stringWriter = new StringWriter();
//        temp.process(null, stringWriter);
//        System.out.println(stringWriter.toString());
////        write.write(code);
////        write.close();
//        System.out.println("已生成"+filePath);
//    }
    public static void createFile(String templatePath, String filePath, Map map) throws IOException, TemplateException {
        new File(new File(filePath).getParent()).mkdirs();
        FileWriter write = new FileWriter(filePath);
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setDirectoryForTemplateLoading(new File(CreateTemplateUtil.class.getResource("/ganerator").getPath()));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        Template temp = cfg.getTemplate(templatePath+".html");
        StringWriter stringWriter = new StringWriter();
        temp.process(map, stringWriter);
        write.write(stringWriter.toString());
        write.close();
        System.out.println("已生成"+filePath);
    }
}
